package com.sayice.robotconflict.view.page

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.window.Dialog
import com.sayice.robotconflict.model.Message
import com.sayice.robotconflict.model.receive.FriendInfo
import com.sayice.robotconflict.model.receive.TeamInviteInfo
import com.sayice.robotconflict.ui.screen.cdp
import com.sayice.robotconflict.view.route.Route
import com.sayice.robotconflict.viewmodel.GameViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 组队房间页面
 *
 * @author shubing
 */
@Composable
fun TeamRoom(viewModel: GameViewModel) {
    val scope = rememberCoroutineScope()
    val teamPlayersInfoState by viewModel.teamPlayersInfoFlow.collectAsState()
    val currentPlayer by derivedStateOf { teamPlayersInfoState.find { it?.id == viewModel.loginInfo.playerId } }
    val friendsState by viewModel.friendsFlow.collectAsState()
    val onlineFriends by derivedStateOf { friendsState.filter { it.online } }
    var openFriendDialog by remember { mutableStateOf(false) }
    Box(modifier = Modifier.fillMaxSize()) {
        Button(
            modifier = Modifier.align(Alignment.TopStart),
            enabled = !(currentPlayer?.ready ?: false),
            onClick = {
                if (currentPlayer != null) {
                    scope.launch(Dispatchers.IO) {
                        viewModel.sendToServer(
                            Message(type = "team", action = "leave", data = currentPlayer!!.roomId)
                        )
                    }
                }
                viewModel.goToPage(Route.HALL)
            }) {
            Text("退出房间")
        }
        if (currentPlayer != null) {
            Text(
                text = "房间号: ${currentPlayer!!.roomId}  ",
                modifier = Modifier.align(Alignment.TopEnd)
            )
            Row(modifier = Modifier.align(Alignment.Center)) {
                for (playerInfo in teamPlayersInfoState) {
                    if (playerInfo == null) {
                        Button(
                            modifier = Modifier.alpha(0.5f),
                            onClick = { openFriendDialog = true }) {
                            Text("+")
                        }
                    } else {
                        Column {
                            Button(
                                onClick = { /*TODO 显示详情*/ },
                                modifier = Modifier.alpha(1.0f)
                            ) {
                                Text(playerInfo.name)
                            }
                            Spacer(modifier = Modifier.height(10.cdp))
                            if (playerInfo.id == viewModel.loginInfo.playerId) {
                                Button(
                                    modifier = Modifier.alpha(if (playerInfo.ready) 0.5f else 1.0f),
                                    onClick = {
                                        scope.launch(Dispatchers.IO) {
                                            viewModel.sendToServer(
                                                Message(
                                                    type = "team",
                                                    action = if (playerInfo.ready) "unready" else "ready",
                                                    data = currentPlayer!!.roomId
                                                )
                                            )
                                        }
                                    }) {
                                    Text(if (playerInfo.ready) "取消" else "准备")
                                }
                            } else {
                                Text(if (playerInfo.ready) "已准备" else "准备中")
                            }
                        }
                    }
                }
            }
            if (openFriendDialog) {
                FriendInviteDialog(
                    onlineFriends = onlineFriends,
                    onDismissRequest = { openFriendDialog = false },
                    roomId = currentPlayer!!.roomId,
                    viewModel = viewModel
                )
            }
        }
    }
}

/**
 * 弹框-邀请好友
 */
@Composable
fun FriendInviteDialog(
    onlineFriends: List<FriendInfo>,
    onDismissRequest: () -> Unit,
    roomId: Int,
    viewModel: GameViewModel
) {
    val scope = rememberCoroutineScope()
    Dialog(onDismissRequest = onDismissRequest) {
        LaunchedEffect(Unit) {
            // 获取好友信息
            viewModel.sendToServer(Message(type = "social", action = "getFriends"))
        }
        Column(
            modifier = Modifier
                .size(width = 1800.cdp, height = 1000.cdp)
                .background(Color.White)
                .padding(10.cdp), horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text("邀请好友:", modifier = Modifier.align(Alignment.Start))
            Spacer(modifier = Modifier.height(10.cdp))
            LazyColumn {
                items(onlineFriends) { friendInfo ->
                    FriendItem(friendInfo = friendInfo, onInvite = {
                        scope.launch(Dispatchers.IO) {
                            viewModel.sendToServer(
                                Message(
                                    type = "team",
                                    action = "invite",
                                    data = TeamInviteInfo(roomId, friendInfo.id)
                                )
                            )
                        }
                        viewModel.showToast("已邀请")
                    })
                }
            }
        }
    }
}

/**
 * 列表项-好友
 */
@Composable
private fun FriendItem(friendInfo: FriendInfo, onInvite: () -> Unit) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Image(
                painter = ColorPainter(Color.Blue), contentDescription = null,
                modifier = Modifier
                    .clip(CircleShape)
                    .size(80.cdp),
                alpha = if (friendInfo.online) 1.0f else 0.5f
            )
            Spacer(modifier = Modifier.width(50.cdp))
            Text(friendInfo.name)
        }
        Button(onClick = onInvite) {
            Text("邀请")
        }
    }
}

